<template>
  <div class="table">
    <el-table
      v-loading="showLoading"
      :data="props.tableData"
      v-bind="$attrs"
      :size="props.small"
      highlight-current-row
      style="width: 100%; height: 100%"
      border
      @current-change="handleCurrentChange"
      class="page-container-table"
      empty="暂无数据"
    >
      <template v-for="(column, index) in props.columns">
        <!-- jsx render -->
        <el-table-column
          v-if="column.render"
          :align="column.align || 'center'"
          v-bind="column"
          :key="index"
        >
          <template #default="scope">
            <extend :render="column.render" :params="scope" />
          </template>
        </el-table-column>
        <!-- 正常 render -->
        <el-table-column
          v-else
          :align="column.align || 'center'"
          v-bind="column"
          :key="index + 1"
        />
      </template>
    </el-table>
    <el-pagination
      class="pages mt16"
      v-if="props.hasPage && tablePage.pageNumber"
      v-model:current-page="tablePage.pageNumber"
      v-model:page-size="tablePage.pageSize"
      :page-sizes="[50, 80, 100, 200]"
      :small="props.size"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tablePage.total"
      @size-change="showSizeChange"
      @current-change="searchRecordData"
    >
      <template v-slot:default> 1 </template>
    </el-pagination>
  </div>
</template>

<script setup lang="ts">
/**
 * 常规表格分页组件
 * @param {type} name 参数名称
 */
import extend from "./extend.vue";

interface tablePage {
  pageNumber: number;
  pageSize: number;
  total: number;
}

let tablePage: tablePage = reactive({
  pageNumber: 1,
  pageSize: 10,
  total: 0,
});
const currentRow = ref();

const props = withDefaults(
  defineProps<{
    showLoading?: boolean;
    hasPage?: boolean;
    page?: tablePage;
    tableData: T[];
    columns: T;
    size?: string;
  }>(),
  {
    showLoading: false,
    hasPage: false,
    page: {} as tablePage,
    tableData: () => [],
    columns: () => [],
    size: "small",
  }
);
if (props.page) {
  tablePage = props.page;
}
const pageText = computed(() => {
  return Math.ceil(tablePage.total / tablePage.pageSize);
});

watch(
  () => props.page,
  () => {
    tablePage = props.page;
  }
);
const emit = defineEmits([
  "pageChange",
  "handleCurrentChange",
  "currentChange",
]);

function onCellChange(a) {
  console.log(a);
}

const handleCurrentChange = (val: any) => {
  currentRow.value = val;
  emit("currentChange", currentRow.value);
};

function searchRecordData() {
  emit("pageChange", props.page);
}
function showSizeChange() {
  emit("pageChange", {
    ...props.page,
    pageNumber: 1,
  });
}
</script>

<style lang="scss" scoped>
.table {
  display: flex;
  flex-direction: column;
}
.pages {
  display: flex;
  justify-content: flex-end;
}
</style>
